package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.role.*;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.service.admin.AdminRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Bowen Deng
 * @since 2022/06/27 16:04
 */
@Service
public class AdminRoleServiceImpl implements AdminRoleService {

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    /**
     * 查询所有的role options
     *
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.vo.role.RoleOptionsVO>
     * @author Bowen Deng
     * @since 2022/06/27 4:21 下午
     */
    @Override
    public CommonData<RoleOptionsVO> listRoleOptions() {
        MarketRoleExample example = new MarketRoleExample();
        int limit = (int) marketRoleMapper.countByExample(example);
        PageHelper.startPage(1, limit);
        List<RoleOptionsVO> voList = marketRoleMapper.selectRoleOptions();
        PageInfo<RoleOptionsVO> voPageInfo = new PageInfo<>(voList);
        CommonData data = CommonData.data(voPageInfo);
        return data;
    }

    /**
     * 查询所有的role,包含模糊查询
     *
     * @param info
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.MarketRole>
     * @author Bowen Deng
     * @since 2022/06/27 7:40 下午
     */
    @Override
    public CommonData<MarketRole> listAllRoles(String name, BasePageInfo info) {
        PageHelper.startPage(info.getPage(), info.getLimit());

        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (!StringUtils.isEmpty(name)) {
            name = "%" + name.trim() + "%";

            criteria.andNameLike(name);
        }
        marketRoleExample.setOrderByClause(info.getSort() + " " + info.getOrder());

        List<MarketRole> marketRoles = marketRoleMapper.selectByExample(marketRoleExample);
        PageInfo<MarketRole> marketRolePageInfo = new PageInfo<>(marketRoles);
        CommonData data = CommonData.data(marketRolePageInfo);

        return data;
    }

    /**
     * 需要查询与数据库里的name是否重复
     * 重复返回100，插入成功返回1，插入失败返回0，数据库错误
     *
     * @param role
     * @return java.lang.Integer
     * @author Bowen Deng
     * @since 2022/06/27 8:02 下午
     */
    @Override
    public Integer addRole(MarketRole role) {
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andNameEqualTo(role.getName());
        List<MarketRole> marketRoles = marketRoleMapper.selectByExample(marketRoleExample);
        if (!marketRoles.isEmpty()) {
            return 100;
        }
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        role.setDeleted(false);
        role.setEnabled(true);
        int affectedRows = marketRoleMapper.insert(role);
        return affectedRows;
    }

    /**
     * 需要查询与数据库里的name是否重复
     * 重复返回100，更新成功返回1，更新失败返回0，数据库错误
     *
     * @param role
     * @return java.lang.Integer
     * @author Bowen Deng
     * @since 2022/06/27 8:22 下午
     */
    @Override
    public Integer updateRole(MarketRole role) {
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andNameEqualTo(role.getName());
        List<MarketRole> marketRoles = marketRoleMapper.selectByExample(marketRoleExample);
        if (!marketRoles.isEmpty() && marketRoles.get(0).getId()!=role.getId()) {
            return 100;
        }
        role.setUpdateTime(new Date());
        int affectedRows = marketRoleMapper.updateByPrimaryKey(role);
        return affectedRows;
    }

    /**
     * 根据deleted判断是否可以删除
     * true可以删除就直接删除，false不可以删除返回100
     *
     * @param role
     * @return java.lang.Integer
     * @author Bowen Deng
     * @since 2022/06/27 8:30 下午
     */
    @Override
    public Integer deleteRole(MarketRole role) {
//        MarketRole marketRole = marketRoleMapper.selectByPrimaryKey(role.getId());
//        if (!marketRole.getDeleted()) {
//            return 100;
//        }
        role.setDeleted(true);
        int affectedRows = marketRoleMapper.updateByPrimaryKeySelective(role);
        return affectedRows;
    }

    /**
     * 根据名字查找role，用来添加后回显
     *
     * @param name
     * @return com.cskaoyan.bean.MarketRole
     * @author Bowen Deng
     * @since 2022/06/27 11:34 下午
     */
    @Override
    public MarketRole selectRoleByName(String name) {
        MarketRoleExample marketRoleExample = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andNameEqualTo(name);
        List<MarketRole> marketRoles = marketRoleMapper.selectByExample(marketRoleExample);
        return marketRoles.get(0);
    }

    /**
     * 这个方法太傻逼了，套三层装三层，查很多次
     * 我胆子比较小，就不用逆向工程了，sql语句自己写
     *
     * @param roleId
     * @return com.cskaoyan.bean.vo.role.PermissionListVO
     * @author Bowen Deng
     * @since 2022/06/27 11:35 下午
     */
    @Override
    public PermissionListVO getPermissions(String roleId) {
        //System
        PermissionListVO permissionListVO = new PermissionListVO();
        ArrayList<PermissionVO> permissionVOS = new ArrayList<>();
        List<PermissionPO> permissionPOList = marketRoleMapper.selectPermissionsByPID(0);
        for (PermissionPO permissionPO : permissionPOList) {
            PermissionVO permissionVO = new PermissionVO();
            permissionVO.setId(permissionPO.getName());
            permissionVO.setLabel(permissionPO.getLabel());
            List<PermissionPO> permissionPOS = marketRoleMapper.selectPermissionsByPID(permissionPO.getId());
            ArrayList<PermissionChildrenVO> permissionChildrenVOS = new ArrayList<>();
            for (PermissionPO po : permissionPOS) {
                PermissionChildrenVO permissionChildrenVO = new PermissionChildrenVO();
                permissionChildrenVO.setId(po.getName());
                permissionChildrenVO.setLabel(po.getLabel());
                List<PermissionPO> poList = marketRoleMapper.selectPermissionsByPID(po.getId());
                ArrayList<PermissionChildrenChildrenVO> permissionChildrenChildrenVOS = new ArrayList<>();
                for (PermissionPO permissionPO1 : poList) {
                    PermissionChildrenChildrenVO permissionChildrenChildrenVO = new PermissionChildrenChildrenVO();
                    permissionChildrenChildrenVO.setId(permissionPO1.getName());
                    permissionChildrenChildrenVO.setLabel(permissionPO1.getLabel());
                    permissionChildrenChildrenVO.setApi(permissionPO1.getApi());
                    permissionChildrenChildrenVOS.add(permissionChildrenChildrenVO);
                }
                permissionChildrenVO.setChildren(permissionChildrenChildrenVOS);
                permissionChildrenVOS.add(permissionChildrenVO);
            }
            permissionVO.setChildren(permissionChildrenVOS);
            permissionVOS.add(permissionVO);
        }
        permissionListVO.setSystemPermissions(permissionVOS);
        //Assigned
        Integer id = Integer.parseInt(roleId);
        List<String> permissions = marketRoleMapper.selectPermissionsByRoleId(id);
        if (permissions.size() == 1 && "*".equals(permissions.get(0))) {
            List<String> allPermissions = marketRoleMapper.selectPermissionsByType(3);
            permissionListVO.setAssignedPermissions(allPermissions);
        } else {
            permissionListVO.setAssignedPermissions(permissions);
        }
        return permissionListVO;
    }

    /**
     * 直接根据前端发过来的String类型的数组更新表
     * 如果全选，发过来的数组大小为104，那么就删掉所有的，直接插入一条*
     * 如果不全选，根据发过来的数组去更新，那么就需要删除掉原来的
     * permission再添加
     *
     * @param update
     * @return java.lang.Integer
     * @author Bowen Deng
     * @since 2022/06/28 9:03 上午
     */
    @Override
    public Integer updatePermissions(UpdatePermissionPO update) {
        String[] permissions = update.getPermissions();
        MarketPermissionExample marketPermissionExample = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = marketPermissionExample.createCriteria();
        criteria.andRoleIdEqualTo(update.getRoleId());
        marketPermissionMapper.deleteByExample(marketPermissionExample);
        if (permissions.length == 104) {
            MarketPermission marketPermission = new MarketPermission();
            marketPermission.setPermission("*");
            marketPermission.setUpdateTime(new Date());
            marketPermission.setAddTime(new Date());
            marketPermission.setDeleted(false);
            marketPermission.setRoleId(update.getRoleId());
            int affectedRows = marketPermissionMapper.insert(marketPermission);
            return affectedRows;
        }
        for (String permission : permissions) {
            MarketPermission marketPermission = new MarketPermission();
            marketPermission.setPermission(permission);
            marketPermission.setRoleId(update.getRoleId());
            marketPermission.setDeleted(false);
            marketPermission.setAddTime(new Date());
            marketPermission.setUpdateTime(new Date());
            int affectedRows = marketPermissionMapper.insert(marketPermission);
        }
        return 1;
    }


}
